package com.example.question.dp.dp4;

/**
 * @Date 2023-07-29
 * @Author Jonathan
 */
public class Code05_10 {
    public static void main(String[] args) {
        Code05_10 code = new Code05_10();
        // mississippi
        // mis*is*p*.
        System.out.println("code.isMatch(\"aa\", \"a*\") = " + code.isMatch("aa", "a*"));
        System.out.println("code.isMatch(\"aaa\", \"ab*ac*a\") = " + code.isMatch("aaa", "ab*ac*a"));
        System.out.println("code.isMatch(\"aaa\", \".*\") = " + code.isMatch("aaa", ".*"));
        System.out.println("code.isMatch(\"abababab\", \".b*\") = " + code.isMatch("abababab", ".b*"));
        System.out.println("code.isMatch(\"mississippi\", \"mis*is*p*.\") = " + code.isMatch("mississippi", "mis*is*p*."));
        System.out.println("code.isMatch(\"aaa\", \"ab*a\") = " + code.isMatch("aaa", "ab*a"));
    }

    /**
     * p 匹配 s
     * p叫模式串
     */
    public boolean isMatch(String s, String p) {
        char[] chars1 = s.toCharArray();
        char[] chars2 = p.toCharArray();
        boolean[][] dp = new boolean[chars1.length + 1][chars2.length + 1];
        dp[0][0] = true;


        // 边界问题
        for (int i = 1; i <= chars2.length; i++) {
            if (chars2[i - 1] == '*' && (i < 2 || dp[0][i - 2])) {
                dp[0][i] = true;
            }
        }
        // abac
        // ab*ac
        for (int i = 1; i <= chars1.length; i++) {
            for (int j = 1; j <= chars2.length; j++) {
                if (chars1[i - 1] == chars2[j - 1] || chars2[j - 1] == '.') {
                    dp[i][j] = dp[i - 1][j - 1];
                } else if (chars2[j - 1] == '*') {
                    if (j >= 2 && chars2[j - 2] == chars1[i - 1] || chars2[j - 2] == '.') {
                        dp[i][j] = dp[i - 1][j] || dp[i][j - 2];
                    } else {
                        dp[i][j] = dp[i][j - 2];
                    }
                }
            }
        }
        return dp[chars1.length][chars2.length];
    }

}
